/**
 * 
 */
package com.alstudio.view.tableview;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alstudio.view.listener.AlViewClickManager;
import com.loovee.imaohu.R;

/**
 * @author alonso lee
 * 
 */
public class ALTableView extends LinearLayout {

	private int mIndexController = 0;
	private LayoutInflater mInflater;
	private LinearLayout mMainContainer;
	private LinearLayout mListContainer;
	private List<IListItem> mItemList;
	private ALTableViewClickListener mClickListener;
	// 分段
	private boolean isSetSector = false;

	private int clickIndex = 0;

	/**
	 * @param context
	 * @param attrs
	 */
	public ALTableView(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		mItemList = new ArrayList<IListItem>();
		mInflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		mMainContainer = (LinearLayout) mInflater.inflate(
				R.layout.tableview_list_container, null);
		LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
				ViewGroup.LayoutParams.FILL_PARENT,
				ViewGroup.LayoutParams.FILL_PARENT);
		addView(mMainContainer, params);
		mListContainer = (LinearLayout) mMainContainer
				.findViewById(R.id.buttonsContainer);
	}

	/**
	 * 加入分段
	 * 
	 * @param segmentations
	 */
	public void addSegmentations(int segmentLayoutId) {
		// this.mSegmentations = segmentLayoutId;
		if (segmentLayoutId != -1) {
			isSetSector = true;
			mItemList.add(new BasicItem(segmentLayoutId));
		}
	}

	/**
	 * 加入分段
	 * 
	 * @param segmentations
	 */
	public void addSegmentations(View segmentView) {
		if (segmentView != null) {
			isSetSector = true;
			mItemList.add(new BasicItem(segmentView));
		}
	}

	/**
	 * 
	 * @param title
	 * @param summary
	 */
	public void addBasicItem(String title) {
		mItemList.add(new BasicItem(title));
	}

	/**
	 * 
	 * @param title
	 * @param summary
	 */
	public void addBasicItem(String title, String summary) {
		mItemList.add(new BasicItem(title, summary));
	}

	/**
	 * 
	 * @param title
	 * @param summary
	 * @param color
	 */
	public void addBasicItem(String title, String summary, int color) {
		mItemList.add(new BasicItem(title, summary, color));
	}

	/**
	 * 
	 * @param drawable
	 * @param title
	 * @param summary
	 */
	public void addBasicItem(int drawable, String title, String summary) {
		mItemList.add(new BasicItem(drawable, title, summary));
	}

	/**
	 * 
	 * @param drawable
	 * @param title
	 * @param summary
	 */
	public void addBasicItem(int drawable, String title, String summary,
			int color) {
		mItemList.add(new BasicItem(drawable, title, summary, color));
	}

	/**
	 * 
	 * @param item
	 */
	public void addBasicItem(BasicItem item) {
		mItemList.add(item);
	}

	/**
	 * 
	 * @param itemView
	 */
	public void addViewItem(ViewItem itemView) {
		mItemList.add(itemView);
	}

	public void commit() {
		mIndexController = 0;
		clickIndex = 0;

		if (mItemList.size() > 1) {
			// 没有分段，那么直接加入
			if (!isSetSector) {
				for (IListItem obj : mItemList) {
					View tempItemView;
					if (mIndexController == 0) {
						tempItemView = mInflater.inflate(
								R.layout.tableview_list_item_top, null);
					} else if (mIndexController == mItemList.size() - 1) {
						tempItemView = mInflater.inflate(
								R.layout.tableview_list_item_bottom, null);
					} else {
						tempItemView = mInflater.inflate(
								R.layout.tableview_list_item_middle, null);
					}
					setupItem(tempItemView, obj, mIndexController);
					tempItemView.setClickable(obj.isClickable());
					mListContainer.addView(tempItemView);
					mIndexController++;
				}
			} else {
				// 有分段，那么循环查找加入
				IListItem obj = null;
				boolean isSetSegmentRequest = false;
				for (int i = 0; i < mItemList.size(); i++) {
					View tempItemView = null;

					obj = mItemList.get(i);

					isSetSegmentRequest = setupSegmentation(obj);

					if (!isSetSegmentRequest) {

						if (isSingleTableView(i)) {
							// 单条
							tempItemView = mInflater.inflate(
									R.layout.tableview_list_item_single, null);
						} else if (isBottomTableView(i)) {
							// 底部
							tempItemView = mInflater.inflate(
									R.layout.tableview_list_item_bottom, null);

						} else if (isTopTableView(i)) {

							// 头部的
							tempItemView = mInflater.inflate(
									R.layout.tableview_list_item_top, null);
						} else {

							// 中部
							tempItemView = mInflater.inflate(
									R.layout.tableview_list_item_middle, null);
						}

						setupItem(tempItemView, obj, mIndexController);
						tempItemView.setClickable(obj.isClickable());
						mListContainer.addView(tempItemView);
						// 仅仅针对非分隔符才记录点击位置
						mIndexController++;
					} else {
						BasicItem tempItem = (BasicItem) obj;

						int res = tempItem.getSegmentLayoutId();
						if (res != -1) {
							tempItemView = mInflater.inflate(res, null);
							mListContainer.addView(tempItemView);
						}
					}

				}
			}

		} else if (mItemList.size() == 1) {
			// when the list has only one item
			View tempItemView = mInflater.inflate(
					R.layout.tableview_list_item_single, null);
			IListItem obj = mItemList.get(0);
			setupItem(tempItemView, obj, mIndexController);
			tempItemView.setClickable(obj.isClickable());
			mListContainer.addView(tempItemView);
		}
	}

	private boolean setupSegmentation(IListItem item) {
		boolean isSegmentView = false;
		if (item instanceof BasicItem) {
			BasicItem tempItem = (BasicItem) item;
			if (tempItem.isSegeMentView()) {
				isSegmentView = true;
			}
		} else if (item instanceof ViewItem) {
			ViewItem tempItem = (ViewItem) item;
		}
		return isSegmentView;
	}

	/**
	 * 判断当前view是否为单条
	 * 
	 * @param currentIndex
	 * @return
	 */
	private boolean isSingleTableView(int currentIndex) {
		// 上一个位置
		int last = currentIndex - 1;
		// 下一个位置
		int next = currentIndex + 1;

		IListItem itemLast = null;
		IListItem itemNext = null;
		if (last != -1) {
			if (last < mItemList.size() - 1) {
				itemLast = mItemList.get(last);
			}
		}

		if (mItemList.size() > next) {
			itemNext = mItemList.get(next);
		}
		if (currentIndex == 0 && itemNext != null
				&& setupSegmentation(itemNext)) {
			return true;
		} else {
			if (itemNext != null && setupSegmentation(itemNext)
					&& itemLast != null && setupSegmentation(itemLast)) {
				return true;
			} else if (currentIndex == mItemList.size() - 1 && itemLast != null
					&& setupSegmentation(itemLast)) {
				return true;
			}
		}

		return false;

	}

	/**
	 * 检测当前是否为底部
	 * 
	 * @param currentIndex
	 * @return
	 */
	private boolean isBottomTableView(int currentIndex) {
		if (currentIndex == 0) {
			// 第一个肯定不是底部
			return false;
		}

		if (isSingleTableView(currentIndex))
			return false;

		// 已经到最后了，那么肯定是底部
		if (currentIndex == mItemList.size() - 1)
			return true;

		int next = currentIndex + 1;
		if (next <= mItemList.size() - 1) {

			IListItem itemNext = null;
			itemNext = mItemList.get(next);
			// 如果下一个位置时分隔符，那么当前肯定是底部
			if (itemNext != null && setupSegmentation(itemNext)) {
				return true;
			}

		}

		return false;
	}

	/**
	 * 检测当前是否为顶部
	 * 
	 * @param currentIndex
	 * @return
	 */
	private boolean isTopTableView(int currentIndex) {

		if (currentIndex == mItemList.size() - 1) {
			// 最后一个肯定不是顶部
			return false;
		}
		if (isSingleTableView(currentIndex))
			return false;

		if (currentIndex == 0)
			return true;

		// 上一个位置
		int last = currentIndex - 1;

		IListItem itemLast = null;
		itemLast = mItemList.get(last);
		// 如果上一个位置时分隔符，那么当前位置肯定是顶部
		if (itemLast != null && setupSegmentation(itemLast)) {
			return true;
		}

		return false;

	}

	private void setupItem(View view, IListItem item, int index) {
		if (item instanceof BasicItem) {
			BasicItem tempItem = (BasicItem) item;
			setupBasicItem(view, tempItem, mIndexController);
		} else if (item instanceof ViewItem) {
			ViewItem tempItem = (ViewItem) item;
			setupViewItem(view, tempItem, mIndexController);
		}
	}

	/**
	 * 
	 * @param view
	 * @param item
	 * @param index
	 */
	private void setupBasicItem(View view, BasicItem item, int index) {

		// 左边的图标
		if (item.getDrawable() > -1) {
			((ImageView) view.findViewById(R.id.image))
					.setBackgroundResource(item.getDrawable());
			view.findViewById(R.id.image).setVisibility(View.VISIBLE);
		} else {
			view.findViewById(R.id.image).setVisibility(View.GONE);
		}

		// 子标题
		if (item.getSubtitle() != null) {
			((TextView) view.findViewById(R.id.subtitle)).setText(item
					.getSubtitle());
		} else {
			((TextView) view.findViewById(R.id.subtitle))
					.setVisibility(View.GONE);
		}

		// 主标题
		((TextView) view.findViewById(R.id.title)).setText(item.getTitle());
		// 主标题颜色
		if (item.getColor() != -1) {
			((TextView) view.findViewById(R.id.title)).setTextColor(item
					.getColor());
		}

		// 右边箭头胖的文字说明
		if (!TextUtils.isEmpty(item.getCountNum())) {
			((TextView) view.findViewById(R.id.itemCount)).setText(item
					.getCountNum());
			view.findViewById(R.id.itemCount).setVisibility(View.VISIBLE);
			// 右边箭头胖的文字说明颜色
			if (item.getItemCountColor() != -1) {
				((TextView) view.findViewById(R.id.itemCount))
						.setTextColor(item.getItemCountColor());
			}

			// 设个背景
			if (item.getItemCountDrawable() != -1) {
				view.findViewById(R.id.itemCount).setBackgroundResource(
						item.getItemCountDrawable());
			}
		} else {
			view.findViewById(R.id.itemCount).setVisibility(View.GONE);
		}

		// 设置mini title
		if (TextUtils.isEmpty(item.getMiniTitle())) {
			// 没有数据，隐藏
			view.findViewById(R.id.mini_title).setVisibility(View.GONE);
		} else {
			view.findViewById(R.id.mini_title).setVisibility(View.VISIBLE);
			((TextView) view.findViewById(R.id.mini_title)).setText(item
					.getMiniTitle());
			// 设置颜色
			if (item.getMiniTtileColor() != -1) {
				((TextView) view.findViewById(R.id.mini_title))
						.setTextColor(item.getMiniTtileColor());
			}

		}

		if (item.isClickable()) {
			view.setTag(clickIndex++);
			view.setOnClickListener(new AlViewClickManager() {

				@Override
				public void onALViewClick(View v) {
					// TODO Auto-generated method stub
					if (mClickListener != null)
						mClickListener.onClick((Integer) v.getTag());

				}
			});
			// view.setOnClickListener(new View.OnClickListener() {
			//
			// @Override
			// public void onClick(View view) {
			// if (mClickListener != null)
			// mClickListener.onClick((Integer) view.getTag());
			// }
			//
			// });
		} else {
			((ImageView) view.findViewById(R.id.chevron))
					.setVisibility(View.GONE);
		}
	}

	/**
	 * 
	 * @param view
	 * @param itemView
	 * @param index
	 */
	private void setupViewItem(View view, ViewItem itemView, int index) {
		if (itemView.getView() != null) {
			LinearLayout itemContainer = (LinearLayout) view
					.findViewById(R.id.itemContainer);
//			if (!itemView.isNeedBg()) {
//				view.setBackgroundDrawable(null);
//			}
			itemContainer.removeAllViews();
			// itemContainer.removeAllViewsInLayout();
			itemContainer.addView(itemView.getView());

			if (itemView.isClickable()) {
				itemContainer.setTag(clickIndex++);
				itemContainer.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View view) {
						if (mClickListener != null)
							mClickListener.onClick((Integer) view.getTag());
					}
				});
			}
		}
	}

	public interface ALTableViewClickListener {
		void onClick(int index);
	}

	/**
	 * 
	 * @return
	 */
	public int getCount() {
		return mItemList.size();
	}

	/**
	 * 
	 */
	public void clear() {
		mItemList.clear();
		mListContainer.removeAllViews();
	}

	/**
	 * 
	 * @param listener
	 */
	public void setClickListener(ALTableViewClickListener listener) {
		this.mClickListener = listener;
	}

	/**
	 * 
	 */
	public void removeClickListener() {
		this.mClickListener = null;
	}

}
